const fs = require('fs');
const path = require('fs');
const { execSync } = require('child_process');
const { versionCompatibility } = require('../src/version-compatibility');
const { versionCore } = require('../src/version-core');

/**
 * 版本化构建器
 */
class VersionBuilder {
  constructor() {
    this.baseDir = path.join(__dirname, '..');
  }

  /**
   * 构建指定版本
   */
  buildVersion(module, version) {
    console.log(`Building ${module}@${version}...`);
    
    // 检查兼容性
    const compatInfo = versionCompatibility[module]?.[version];
    if (!compatInfo) {
      throw new Error(`Invalid version ${version} for module ${module}`);
    }

    // 设置依赖版本
    this.setDependencyVersions(compatInfo.dependencies);

    // 执行构建
    execSync(`npm run build:${module}`, { 
      stdio: 'inherit',
      cwd: this.baseDir
    });

    console.log(`Successfully built ${module}@${version}`);
  }

  /**
   * 设置依赖版本
   */
  setDependencyVersions(dependencies) {
    for (const [depModule, version] of Object.entries(dependencies)) {
      const module = depModule.replace('@', '');
      versionCore.upgradeCoreVersion(module, version);
    }
  }
}

// 命令行参数处理
const args = process.argv.slice(2);
if (args.length < 2) {
  console.error('Usage: node scripts/build-version.js <module> <version>');
  process.exit(1);
}

// 执行构建
new VersionBuilder().buildVersion(args[0], args[1]);